﻿using Prism.Commands;
using Prism.Events;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZoneLineNew.Common;
using ZoneLineNew.Core.Extensions;
using ZoneLineNew.Models.Dto;
using ZoneLineNew.Models.Entity.BaseInfo;
using ZoneLineNew.Services.DB;
using ZoneLineNew.Services.Message;
using ZoneLineNew.ViewModelBase;

namespace ZoneLineNew.ViewModels {


    public class RecipeSettingViewModel : NavigationViewModel {

        public RecipeSettingViewModel(
            IRegionManager regionManager, 
            IDialogService dialog, 
            IMessageService messageBox, 
            IEventAggregator eventAggregator, 
            IDbOperate<IFreeSqlMainContext> dbOperate) 
            : base(regionManager, dialog, messageBox, eventAggregator, dbOperate) {
        
        }

        #region Props

        private string _searchText;

        public string SearchText
        {
            get { return _searchText; }
            set { _searchText = value; base.RaisePropertyChanged(); }
        }

        private string _searchStationCode;

        public string SearchStationCode {
            get { return _searchStationCode; }
            set { _searchStationCode = value; base.RaisePropertyChanged(); }
        }

        private ObservableCollection<RecipeDto> _recipes = new ObservableCollection<RecipeDto>();

        public ObservableCollection<RecipeDto> Recipes
        {
            get { return _recipes; }
            set { _recipes = value; base.RaisePropertyChanged(); }
        }

        private ObservableCollection<ProductEntity> _products = new ObservableCollection<ProductEntity>();

        public ObservableCollection<ProductEntity> Products
        {
            get { return _products; }
            set { _products = value; base.RaisePropertyChanged(); }
        }

        private ObservableCollection<string> _stationCodes = new ObservableCollection<string>();

        public ObservableCollection<string> StationCodes {
            get { return _stationCodes; }
            set { _stationCodes = value; base.RaisePropertyChanged(); }
        }
        

        private RecipeEntity _selectRecipeEntity;

        public RecipeEntity SelectRecipeEntity
        {
            get { return _selectRecipeEntity; }
            set { _selectRecipeEntity = value; base.RaisePropertyChanged(); }
        }

        private RecipeEntity _recipeEntity;

        public RecipeEntity RecipeEntity
        {
            get { return _recipeEntity; }
            set { _recipeEntity = value; base.RaisePropertyChanged(); }
        }

        private bool _isOpen;

        public bool IsOpen
        {
            get { return _isOpen; }
            set { _isOpen = value; base.RaisePropertyChanged(); }
        }
        #endregion


        #region Commands

        public DelegateCommand SearchCommand => new DelegateCommand(() => {
            LoadData();
        });
        

        public DelegateCommand AddRecipeCommand => new DelegateCommand(() => {
            IsOpen = !IsOpen;
            RecipeEntity = new RecipeEntity();
            RecipeEntity.CreateTime = DateTime.Now;
        });

        public DelegateCommand<RecipeDto> EditRecipeCommand => new DelegateCommand<RecipeDto>((rhs) => {
            IsOpen = true;
            RecipeEntity = rhs;
        });

        public DelegateCommand<RecipeDto> DeleteRecipeCommand => new DelegateCommand<RecipeDto>((rhs) => {
            var ask = _message.Ask("确认是否复删除此配方数据？");
            if (ask == System.Windows.MessageBoxResult.OK) {
                var res = _mainDbOperate.DeleteModel<RecipeEntity>(o => o.Id == rhs.Id);
                if (res) {
                    _message.GrowSuccess("删除成功！");
                    LoadData();
                } else {
                    _message.GrowError("删除失败！");
                }
            }
        });


        public DelegateCommand SaveParamsCommand => new DelegateCommand(() =>
        {
            //if (RecipeEntity == null || string.IsNullOrEmpty(RecipeEntity.IP))
            //{
            //    _message.Warning("设备IP不能为空！");
            //    return;
            //}

            if (RecipeEntity == null || string.IsNullOrEmpty(RecipeEntity.StationCode)) {
                _message.Warning("设备编号不能为空！");
                return;
            }

            if (RecipeEntity == null || string.IsNullOrEmpty(RecipeEntity.RecipeName))
            {
                _message.Warning("配方名称不能为空！");
                return;
            }

            if (RecipeEntity == null || string.IsNullOrEmpty(RecipeEntity.RecipeNumber))
            {
                _message.Warning("配方编号不能为空！");
                return;
            }

            if (RecipeEntity == null || string.IsNullOrEmpty(RecipeEntity.ProductID.ToString()))
            {
                _message.Warning("请选择产品！");
                return;
            }

            var res = _mainDbOperate.GetFreeSql().InsertOrUpdate<RecipeEntity>().SetSource(RecipeEntity).ExecuteAffrows();
            if (res > 0)
            {
                _message.GrowSuccess("保存成功！");
                IsOpen = false;
                LoadData();
            }
        });


        #endregion


        protected override void OnViewLoaded() {
            LoadData();

            var plist = _mainDbOperate.GetModelList<ProductEntity>(o => true);
            Products.Clear();
            Products.AddRange(plist);

            StationCodes.Clear();
            if (Cache.IsHopStaion) {
                StationCodes.Add("OP620");
                StationCodes.Add("OP640");
            } else if (Cache.IsQopStaion) {
                StationCodes.Add("OP570");
                StationCodes.Add("OP580-1");
                StationCodes.Add("OP580-2");
            }

            base.OnViewLoaded();
        }

        private void LoadData() {
            var list = _mainDbOperate.GetFreeSql().Select<RecipeEntity, ProductEntity>()
                  .LeftJoin((a, b) => a.ProductID == b.Id)
                  .WhereIf(!string.IsNullOrEmpty(SearchText), (a, b) => a.RecipeName.Contains(SearchText) || b.ProductName.Contains(SearchText))
                  .WhereIf(!string.IsNullOrEmpty(SearchStationCode), (a, b) => a.StationCode == SearchStationCode)
                  .ToList((a, b) => new RecipeDto {
                      Id = a.Id,
                      ProductID = a.ProductID,
                      RecipeName = a.RecipeName,
                      RecipeNumber = a.RecipeNumber,
                      ProductName = b.ProductName,
                      ProductModel = b.Model,
                      IP = a.IP,
                      ProductWorkDirection = b.WorkDirection,
                      Remark = a.Remark
                  }).OrderByDescending(o => o.Id);
            Recipes.Clear();
            Recipes.AddRange(list);
        }
    }
}
